package stuy;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet(name = "cookieServlet03", urlPatterns = "/cookie03")
public class cookieServlet03 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //cookie 可以设置存活时间
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String val =URLEncoder.encode("中文","utf8");
        //URl编码解决了cookie中不能储存中文
        Cookie cookie =new Cookie("cookie03","val");
        //存活时间的单位是 秒
        /*
        maxAge:>0表示cookie 存活多少秒,到时间浏览器自动删除
        该cookie
        maxAge:<0 无论设置成多少,都表示货到浏览器关闭 默认值就是-1
        maxAge:=0 表示告诉浏览器立即删除这个cookie
         */
        cookie.setMaxAge(20);

        response.addCookie(cookie);
        //让cookie可以在各个二级域名之间共享
        cookie.setDomain("baidu.com");
       /*
       .com顶级域名
       baidu.com 一级域名
       www.baidu.com 二级域名
       pan.baidu.com 二级域名
        */

       PrintWriter writer=response.getWriter();
        for (Cookie c : request.getCookies()) {
            String name=c.getName();
            String value=c.getValue();
            writer.println(name+"::"+value);

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
